/**
 * 代码缺陷相关中间件
 *
 * Created by yangyunze on 2021/05/31.
 */
const codeDefects = require('../../models/code-defects');
const projects = require('../../models/projects');
const projectVersions = require('../../models/project-versions');
const files = require('../../models/files');
const PhoenixError = require('./../../models/phoenix-error');

function requireDefectExist(req, res, next) {
  const { defectId } = req.params;
  if (!defectId) {
    next(new PhoenixError('invalid request', 'Missing parameters. "defectId" is required'));
    return;
  }
  codeDefects.getCodeDefect(defectId)
    .then((defect) => {
      if (!defect) {
        return Promise.reject(new PhoenixError('not found', 'Not found, code defect not found'));
      }
      req.$defect = defect;
      const { projectId, versionId, fileId } = defect;
      const promises = [
        projects.getProject(projectId),
        projectVersions.getVersion(versionId),
        files.getFile(fileId),
      ];
      return Promise.all(promises);
    })
    .then(([project, projectVersion, file]) => {
      if (!projectVersion) {
        return Promise.reject(new PhoenixError('not found', 'Not found, projectVersion not found'));
      }
      if (!project) {
        return Promise.reject(new PhoenixError('not found', 'Not found, project not found'));
      }
      req.$project = project;
      req.$projectVersion = projectVersion;
      req.$file = file;
      return Promise.resolve();
    })
    .then(() => {
      next();
    })
    .catch((err) => {
      next(new PhoenixError(err));
    });
}

module.exports = {
  requireDefectExist,
};
